import { getLogs, updateHaru } from '../../utils/haru'

interface History {
    author: number
    pid: string
    user: number
    status: string
}

const HISTORY_HARU_ID = 11
let historys: History[] | undefined

async function getHistorys(): Promise<History[]> {
    if (historys === undefined) {
        const logs = (await getLogs()).filter(log => log.note === HISTORY_HARU_ID && log.action === 'modify')
        historys = logs.map(log => {
            const { pid, user, status } = JSON.parse(log.content)
            return { author: log.author, pid, user, status }
        })
    }
    return historys
}

async function recordHistory(pid: string, user: number, status: string): Promise<void> {
    await updateHaru(HISTORY_HARU_ID, JSON.stringify({ pid, user, status }))
    historys = undefined
}

export { getHistorys, recordHistory }
